package com.yds.bluetooth

import android.annotation.SuppressLint
import android.app.Activity
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothGatt
import android.bluetooth.BluetoothGattCallback
import android.bluetooth.BluetoothGattCharacteristic
import android.bluetooth.BluetoothManager
import android.bluetooth.BluetoothProfile
import android.bluetooth.le.ScanCallback
import android.bluetooth.le.ScanFilter
import android.bluetooth.le.ScanResult
import android.bluetooth.le.ScanSettings
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.util.Log
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
import java.lang.ref.WeakReference
import java.util.UUID


/**
 * 作者:     YDS
 * 创建时间: 2024/7/6 11:22
 * 页面描述: 蓝牙帮助类
 */
@Suppress("unused")
object BluetoothHelper : LifecycleObserver {

    private const val TAG = "YDSimon"
    private const val REQUEST_ENABLE_BT = 998

    private var activityWeakReference: WeakReference<FragmentActivity>? = null

    private var bluetoothManager: BluetoothManager? = null
    private var bluetoothAdapter: BluetoothAdapter? = null

    /*** 作者: YDS 时间: 2024/7/6 10:28 描述: 检查是否支持蓝牙功能 ***/
    fun checkBluetoothIsSupported(context: FragmentActivity, isClassics: Boolean = true): Boolean {
        activityWeakReference = WeakReference(context)
        activityWeakReference?.get()?.let {
            return it.packageManager.hasSystemFeature(if (isClassics) PackageManager.FEATURE_BLUETOOTH else PackageManager.FEATURE_BLUETOOTH_LE)
        } ?: run {
            return false
        }
    }

    /*** 作者: YDS 时间: 2024/7/6 10:54 描述: 实例化蓝牙相关配置 ***/
    @SuppressLint("MissingPermission")
    fun init(context: FragmentActivity): Boolean {
        activityWeakReference = WeakReference(context)
        activityWeakReference?.get()?.let {
            // 获取蓝牙管理器
            bluetoothManager = context.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
            // 获取蓝牙适配器
            bluetoothAdapter = bluetoothManager?.adapter
            // 检查蓝牙是否已开启
            if (null == bluetoothAdapter || !bluetoothAdapter!!.isEnabled) {
                // 尝试开启蓝牙
                val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
                context.startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT)
                return false
            }
        } ?: run {
            return false
        }

        return true
    }

    /*** 作者: YDS 时间: 2024/7/6 10:57 描述: 蓝牙打开接口回调 ***/
    fun onActivityResultForBluetooth(requestCode: Int, resultCode: Int): Boolean {
        if (requestCode == REQUEST_ENABLE_BT) {
            return resultCode == Activity.RESULT_OK
        }
        return false
    }

    private var scanCallback: ScanCallback? = null

    /*** 作者: YDS 时间: 2024/7/6 16:06 描述: 开始扫描蓝牙设备 ***/
    @SuppressLint("MissingPermission")
    fun startBleScan(callback: (List<BluetoothDevice>) -> Unit) {
        val mListDevices = mutableListOf<BluetoothDevice>()
        scanCallback = object : ScanCallback() {
            @SuppressLint("MissingPermission")
            override fun onScanResult(callbackType: Int, result: ScanResult) {
                super.onScanResult(callbackType, result)

                val device = result.device
                device.name?.let {
                    val deviceAddress = device.address
                    mListDevices.any {
                        it.address == deviceAddress
                    }.apply {
                        if (!this ) {//&& device.name == "EDC30-No1"
                            mListDevices.add(device)
                            callback(mListDevices)
//                            Log.d(TAG, "发现BLE设备: 名称 - $deviceName, 地址 - $deviceAddress, 信号强度 - $rssi")
                        }
                    }
                }
            }

            override fun onBatchScanResults(results: MutableList<ScanResult>) {
                super.onBatchScanResults(results)
                // 如果需要处理批量扫描结果，可以在此处进行
            }

            override fun onScanFailed(errorCode: Int) {
                super.onScanFailed(errorCode)
                Log.w(TAG, "BLE扫描失败，错误代码: $errorCode")
                // 根据错误码处理扫描失败情况
            }
        }
        val settings = ScanSettings.Builder()
            // 或选择其他适合的扫描模式
            .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
            .build()
        // 可以添加过滤条件，如特定的服务UUID等
        val filters = mutableListOf<ScanFilter>()

        bluetoothAdapter?.bluetoothLeScanner?.startScan(filters, settings, scanCallback)
    }


    /*** 作者: YDS 时间: 2024/7/6 16:06 描述: 停止扫描蓝牙设备 ***/
    @SuppressLint("MissingPermission")
    fun stopBleScan() {
        bluetoothAdapter?.bluetoothLeScanner?.stopScan(scanCallback)
    }

    private val mListUuids = mutableListOf<UUID>()
    private var mBluetoothGatt: BluetoothGatt? = null

    /*** 作者: YDS 时间: 2024/7/6 16:15 描述: 连接蓝牙设备 ***/
    @SuppressLint("MissingPermission")
    fun connectBleDevice(context: FragmentActivity, bleDevice: BluetoothDevice?) {
        activityWeakReference = WeakReference(context)
        activityWeakReference?.get()?.let {
            bleDevice?.let {
                mBluetoothGatt = it.connectGatt(context, false, object : BluetoothGattCallback() {
                    @SuppressLint("MissingPermission")
                    override fun onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) {
                        when (newState) {
                            BluetoothProfile.STATE_CONNECTED -> {
                                Log.i(TAG, "已连接到GATT服务器。")
                                gatt.discoverServices() // 连接成功后触发服务发现
                            }

                            BluetoothProfile.STATE_DISCONNECTED -> {
                                Log.i(TAG, "已断开与GATT服务器的连接。")
                                // 在此处处理断开连接的逻辑
                            }
                        }
                    }

                    override fun onServicesDiscovered(gatt: BluetoothGatt, status: Int) {
                        if (status == BluetoothGatt.GATT_SUCCESS) {
                            mListUuids.clear()
                            mBluetoothGatt = gatt
                            val services = gatt.services
                            mListUuids.addAll(services.map { service ->
                                service.uuid
                            })
                            /*GlobalScope.launch {
                               BLENotificationHandler().enableAllNotifications(gatt)
                               repeat(1000){
                                   delay(2000)
                                   BLEDataReader().readFromAllReadableCharacteristics(gatt)
                               }
                           }*/
                        } else {
                            Log.w(TAG, "onServicesDiscovered 接收到状态码: $status")
                        }
                    }

                    override fun onCharacteristicWrite(gatt: BluetoothGatt?, characteristic: BluetoothGattCharacteristic?, status: Int) {
                        super.onCharacteristicWrite(gatt, characteristic, status)
                        if (status == BluetoothGatt.GATT_SUCCESS) {
                            // 数据写入成功
                            Log.w(TAG, "数据写入成功")
                        }
                    }


                    override fun onCharacteristicRead(gatt: BluetoothGatt?, characteristic: BluetoothGattCharacteristic?, status: Int) {
                        super.onCharacteristicRead(gatt, characteristic, status)
                        // 接收到的数据
                        val data = characteristic!!.value
                        Log.w(TAG, "接收到的数据 ${data.size} ${DataConvert.toHexString(data)}")
                    }

                    // 根据需要覆盖其他相关函数，如onCharacteristicRead、onCharacteristicWrite等
                })
            }
        }
    }

    /*** 作者: YDS 时间: 2024/7/8 13:07 描述: 写数据 ***/
    fun writeBleData(msg: String) {
        BLEDataWriter().sendDataToAllWritableCharacteristics(mBluetoothGatt, DataConvert.hexStringToBytes(msg))
    }

    /*** 作者: YDS 时间: 2024/7/6 16:21 描述: 断开连接蓝牙设备 ***/
    @SuppressLint("MissingPermission")
    fun disconnectBleDevice(): Boolean {
        mBluetoothGatt?.let {
            try {
                val localMethod = it.javaClass.getMethod("refresh", *arrayOfNulls(0))
                val bool = localMethod.invoke(it, *arrayOfNulls(0)) as Boolean
                Log.i(TAG, "Ble释放内存 $bool")
                return bool
            } catch (localException: Exception) {
                Log.i(TAG, "disconnectBleDevice Exception $localException")
            } finally {
                it.disconnect()
                it.close()
            }
        }

        return false
    }



    /*** 作者: YDS 时间: 2024/7/6 10:37 描述: 关闭蓝牙 ***/
    @SuppressLint("MissingPermission")
    fun closeBluetooth() {
        bluetoothAdapter?.disable()
    }

    /*** 作者: YDS 时间: 2024/7/6 13:14 描述: 销毁 ***/
    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    fun onDestroy() {
        activityWeakReference = null
    }

}